import React, { lazy, Suspense } from 'react'
import { RouteObject, useRoutes } from 'react-router-dom'
import Layout from '@/containers/BaseLayout/index'
import { handleRouters, type RouteObjectObj } from './utils'
import systemRouters from './system'
import supplierRouters from './supplier'
import purchaseRouters from './purchase'
import reorderRouters from './reorder'
import monitorRouters from './monitor'
import dashboardRouters from './dashboard'
import fabricRouters from './fabric'
import logisticsRouters from './logistics'
import deskRouters from './desk'
const taskCenter = [
  {
    name: '任务中心',
    path: '/task/center/list',
    resourcePath: '../pages/Task/center/index.tsx',
  },
]
const combineRouters = [
  ...systemRouters,
  ...supplierRouters,
  ...purchaseRouters,
  ...reorderRouters,
  ...taskCenter,
  ...monitorRouters,
  ...dashboardRouters,
  ...fabricRouters,
  ...logisticsRouters,
  ...deskRouters,
]
function AppRouter() {
  const allRouters: RouteObjectObj[] = [
    {
      element: <Layout />,
      path: '',
      children: handleRouters(combineRouters),
    },
    {
      path: '/login',
      component: lazy(() => import('@/pages/Login')),
    },
    {
      path: '/print',
      component: lazy(() => import('@/components/Print')),
    },
    {
      path: '/404',
      component: lazy(() => import('@/components/NotFound')),
    },
    {
      path: '/403',
      component: lazy(() => import('@/components/NotPermission')),
    },
    {
      path: '*',
      component: lazy(() => import('@/components/NotFound')),
    },
  ]
  const approuter: React.ReactElement | null = useRoutes(syncRouter(allRouters))
  return approuter
}
const syncRouter = (table: RouteObjectObj[]): RouteObject[] => {
  return table?.map((route) => ({
    path: route.path,
    element: route.element
      ? route.element
      : route.component && (
          <Suspense fallback={<div id="page_loading_wrap" />}>
            <route.component />
          </Suspense>
        ),
    children: route.children && syncRouter(route.children),
  }))
}

export default AppRouter
